/*
 * Author: Jeffrey van de Glind;
 */

/* Start external
 * Src: http://snipplr.com/view/19838/get-url-parameters/
 */
function getUrlVars()
{
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
      vars[key] = value;
  });
  return vars;
}
/*
 * End external
 */
 
function CardScroller(divname, url, GET_parameters)
{
  this.HALFCARDWIDTH = 111;
  this.HALFCARDHEIGHT = 111;

  var MAXCARDS;
  var MIDCARD;
  var CONTAINERMID_WIDTH;
  var CONTAINERMID_HEIGHT;
  var LEFTLOCATION;
  var TOPLOCATION;
    
  var startTouchLocation;

  this.temp_x = 0;
  this.temp_y = 0;
  
  this.amount_of_cards = 0;

  this.current_card = 0;

  this.cards = new Array();

  this.GET_parameters = GET_parameters;
  this.url = url;

  this.card_container = document.getElementById(divname);

  if(!this.card_container) //container not found, just ignore
  {
    return;
  }
  
  this.direction = "horizontal";
  this.showTooltip = false;
  this.showFooter = false;
  
  this.setDirection = function(_direction)
  {
    this.direction = _direction;
  }
  
  this.setShowTooltip = function(_showTooltip)
  {
    this.showTooltip = _showTooltip;
  }
  
  this.setShowFooter = function(_showFooter)
  {
    this.showFooter = _showFooter;
  }
  
  this.update_cards = function()
  {
    //get table of distributions
    centercard = this.cards[this.current_card];
    if(centercard) //check if there is actually a card in the center
    {
      this.getDistribution(centercard.id);
    }

    for(var a = 0 ; a < this.MAXCARDS ; a++)
    {
      var card = $('#'+this.card_container.id+'_card_'+a);
      var url = $('#'+this.card_container.id+'_card_'+a+'_link');

      //MAXCARD = 5
      //MIDCARD = MAX/2 rounded down: 5/2 -> 2
      //                    MIDCARD
      //                      V
      //box index (a): [0][1][2][3][4]
      //display:       [ ][ ][M][ ][ ]
      //card index:    [ ][0][1][2][3]
      //card index:    [5][6][7][8][9]
      //card index:    [7][8][9][ ][ ]

      var cardindex = this.current_card - this.MIDCARD + a; //box[0] starts at (middle card - index of middle card).
      if(cardindex >= 0 && cardindex < this.amount_of_cards)
      {
        card.attr('src', ""); //hack to show no image when loading image for box
        card.attr('src', this.cards[cardindex].src);
        card.attr('alt', this.cards[cardindex].name);
        url.attr('href', this.cards[cardindex].url);
      }
      else //display something default;
      {
        card.attr('src', "./images/default.jpg");
        card.attr('alt', "Magic the Gathering");
        url.attr('href', null);
      }
    }
  };

  this.printTooltip = function(a)
  {
    return '<div id="'+this.card_container.id+'_tooltip_'+a+'" class="tooltip"></div>';
  }
  
  this.printFooter = function(a)
  {
    return '<div class="card_image_footer"> \
              <p class="total_amount_indicator" id="'+this.card_container.id+'_total_'+a+'"> \
                 \
              </p> \
            </div>';
  }
  
  this.scroll_to = function(position)
  {
    if(typeof position == "undefined") return;
    
    var temp_current = this.current_card;
    
    this.current_card = position;
    if(this.current_card < 0)
    {
      this.current_card = 0;
    }
    else if(this.current_card > this.cards.length-1)
    {
      this.current_card = this.cards.length-1;
    }
    
    if(temp_current !== this.current_card)
    {
      this.update_cards();
    }
  }
  
  this.scroll_with = function(offset)
  {
    this.scroll_to(this.current_card + offset);
  };

  this.create_boxes = function()
  {
    //see if it's mobile
    var ua = navigator.userAgent.toLowerCase();
    if(this.direction == "vertical")
    {
      this.MAXCARDS = (ua.indexOf("mobile") > 1) ? 3 : Math.floor((Math.floor(this.card_container.offsetHeight) - 310)/35) - 1;
    }
    else
    {
      this.MAXCARDS = (ua.indexOf("mobile") > 1) ? 3 : Math.floor((Math.floor(this.card_container.offsetWidth) - 223)/50) - 1;
    }

    this.MIDCARD = Math.floor(this.MAXCARDS/2);
    this.CONTAINERMID_WIDTH = Math.floor(this.card_container.offsetWidth/2);
    this.CONTAINERMID_HEIGHT = Math.floor(this.card_container.offsetHeight/2);
    this.LEFTLOCATION = this.CONTAINERMID_WIDTH - this.HALFCARDWIDTH;
    this.TOPLOCATION = this.CONTAINERMID_HEIGHT - this.HALFCARDHEIGHT;

    //create boxes
    var boxes = "<p id=\"card_expansion\"></p>";
    for(var a = 0 ; a < this.MAXCARDS ; a++)
    {
      //HTML ID
      var boxID = this.card_container.id+"_box_"+a;
      var linkID = this.card_container.id+"_card_"+a+"_link";
      var imgID = this.card_container.id+"_card_"+a;

      //position and size of IMG
      var offset_from_mid = Math.abs(a - this.MIDCARD);
      var card_height = 310 - 10*offset_from_mid;
      var card_width = 223 - 8*offset_from_mid;
      var zIndex = this.MAXCARDS - offset_from_mid;
      var height = card_height+'px';
      var width = card_width+'px';

      if(this.direction == "vertical")
      {
        var top = Math.floor(this.TOPLOCATION + (40*(card_height)/310)*(a - this.MIDCARD))+"px";
        var left = this.LEFTLOCATION+Math.floor(4*offset_from_mid)+"px";
      }
      else
      {
        var top = Math.floor(5*offset_from_mid)+30+"px";
        var left = Math.floor(this.LEFTLOCATION + (50*(card_height)/310)*(a - this.MIDCARD))+"px";
      }

      boxes += '<div id="'+boxID+'" class="card_image" style="width:'+width+'; height:'+height+'; z-index:'+zIndex+'; left:'+left+'; top:'+top+'; background:black"> \
                  <a id="'+linkID+'" href="."> \
                    <img src="./images/default.jpg" id="'+imgID+'" width="'+width+'" height="'+height+'" alt="card_background"> \
                  </a>';
      if(a === this.MIDCARD && this.showTooltip == true)
      {
        boxes += this.printTooltip(a);
      }
      if(a === this.MIDCARD && this.showFooter == true)
      {
        boxes += this.printFooter(a);
      }
      boxes += "</div>";
    }

    boxes += '<p id="collection_total" style="position:absolute; right:0px; bottom:0px; padding:5px; margin:0px;">Total: ()</p>';
    
    this.card_container.innerHTML = boxes;
    
    var mid_tooltip = document.getElementById(this.card_container.id+'_tooltip_'+ this.MIDCARD);
    if(mid_tooltip)
    {
      var self = this;

      //set default scrolling when in tooltip
      mid_tooltip.addEventListener("mousemove", function(){
        self.card_container.removeEventListener("mousewheel", self, false);
        self.card_container.removeEventListener("mousedown", self, false);
        self.card_container.removeEventListener("DOMMouseScroll", self, false);
      }, false);

      //set card scrolling when moving out
      mid_tooltip.addEventListener("mouseout", function(){
        self.card_container.addEventListener("mousewheel", self, false);
        self.card_container.addEventListener("mousedown", self, false);
        self.card_container.addEventListener("DOMMouseScroll", self, false);
      }, false);
    }
  };

  /*
   * Get the cards from database and create the boxes to show them in.
   */
  this.initialize_cards = function(startPosition)
  {
    startPosition = typeof startPosition !== 'undefined' ? startPosition : 0;
  
    this.create_boxes();

    var type = this.GET_parameters['type'];
    var id = this.GET_parameters['id'];

    var input = "";

    var interval = 5;
    var currentPage = 0;
    var returnedCards = 0;
    
    for (GET_parameter in GET_parameters)
    {
      input += GET_parameter + "=" + GET_parameters[GET_parameter] + "&";
    }
    
    this.getCards(this.url + '?' + input, 0, 5, startPosition);
    this.getCollectionSize();
  };
  
  this.getCards = function(url, page, pagesize, startPosition)
  {
    var self = this;
    input = 'PAGE='+page+'&PSIZE='+pagesize+'&';
  
    $.getJSON(url + input, function(data) {
      //store them in array
      self.cards = self.cards.concat(data);
      //set the length (to prevent calculations later)
      self.amount_of_cards = self.cards.length;
      //update the pictures
      self.update_cards();
      //go to startposition
      if(self.amount_of_cards > startPosition && self.current_card == 0)
      {
        self.scroll_to(startPosition);
      }
      
      if(data.length >= 5)
      {
        self.getCards(url, page+1, pagesize, startPosition);
      }
    });
  }
  
  this.getDistribution = function(cardid)
  {
    var self = this;

    try
    {
      //get distribtion
      ajaxRequest_distribution = new XMLHttpRequest();
      ajaxRequest_distribution.onreadystatechange = function()
      {
        if(ajaxRequest_distribution.readyState === 4)
        {
          if(ajaxDisplay = document.getElementById(self.card_container.id+'_tooltip_'+self.MIDCARD))
          {
            ajaxDisplay.innerHTML=ajaxRequest_distribution.responseText;
          }
        }
      };
      ajaxRequest_distribution.open("GET", "./php_scripts/getDistribution.php?cardid="+cardid, true);
      ajaxRequest_distribution.send(null);

      //get total
      ajaxRequest_total = new XMLHttpRequest();
      ajaxRequest_total.onreadystatechange = function()
      {
        if(ajaxRequest_total.readyState === 4)
        {
          if(ajaxDisplay = document.getElementById(self.card_container.id+'_total_'+self.MIDCARD))
          {
            ajaxDisplay.innerHTML="<b><span id=\"total_"+cardid+"\">"+ajaxRequest_total.responseText+"</span></b>";
          }
        }
      };
      var urlVars = getUrlVars();
      if(urlVars.collectionId)
      {
        var collectionId = parseInt(urlVars.collectionId);
      }
      else if(urlVars.deckId)
      {
        var collectionId = parseInt(urlVars.deckId);
      }
      ajaxRequest_total.open("GET", "./php_scripts/get_total_amount.php?cardid="+cardid+"&collectionid="+collectionId, true);
      ajaxRequest_total.send(null);

      //get expansion
      ajaxRequest_expansion = new XMLHttpRequest();
      ajaxRequest_expansion.onreadystatechange = function()
      {
        if(ajaxRequest_expansion.readyState === 4)
        {
          if(ajaxDisplay = document.getElementById('card_expansion'))
          {
            ajaxDisplay.innerHTML = ajaxRequest_expansion.responseText;
          }
        }
      }
      ajaxRequest_expansion.open("GET", "./php_scripts/get_expansion.php?cardid="+cardid, true);
      ajaxRequest_expansion.send(null);
    }
    catch (e)
    {
      alert("error"+e);
    }
  };

  this.getCollectionSize = function()
  {
    var urlVars = getUrlVars();
    if(urlVars.collectionId)
    {
      var collectionId = parseInt(urlVars.collectionId);
    }
    else if(urlVars.deckid)
    {
      var collectionId = parseInt(urlVars.deckid);
    }
  
    //get distribtion
    ajaxRequest_distribution = new XMLHttpRequest();
    ajaxRequest_distribution.onreadystatechange = function()
    {
      if(ajaxRequest_distribution.readyState === 4)
      {
        if(ajaxDisplay = document.getElementById('collection_total'))
        {
          ajaxDisplay.innerHTML=ajaxRequest_distribution.responseText;
        }
      }
    };
    ajaxRequest_distribution.open("GET", "./php_scripts/get_collection_size.php?collectionId="+collectionId, true);
    ajaxRequest_distribution.send(null);
  }
  
  this.relocate = function(e)
  {
    e.preventDefault();

    if(e.which < 2 || typeof e.touches !== 'undefined')
    {
      if(this.direction == "vertical")
      {
        var currentlocation = (typeof e.touches !== 'undefined') ? e.touches[0].pageY : e.clientY;
        if(Math.abs(this.temp_y - currentlocation) > 10)
        {
          this.startTouchLocation = false;
          this.scroll_with(Math.floor((this.temp_y - currentlocation)%10));
          this.temp_y = currentlocation;
        }
      }
      else
      {
        var currentlocation = (typeof e.touches !== 'undefined') ? e.touches[0].pageX : e.clientX;
        if(Math.abs(this.temp_x - currentlocation) > 10)
        {
          this.startTouchLocation = false;
          this.scroll_with(Math.floor((this.temp_x - currentlocation)%10));
          this.temp_x = currentlocation;
        }
      }
    }
    else
    {
      this.end_mouse;
    }
  };

  //callbacks
  //touch
  this.start_touch = function(e)
  {
    this.temp_x = e.touches[0].pageX;
    this.temp_y = e.touches[0].pageY;

    e.preventDefault();
    document.onselectstart = function() {return false;};

    this.card_container.addEventListener("touchmove", this, false);

    this.startTouchLocation = true;
  };

  this.end_touch = function(e)
  {
    e.preventDefault();
    document.onselectstart = null;

    this.card_container.removeEventListener("touchmove", this, false);
    
    if(this.startTouchLocation)
    {
      url = document.getElementById(this.card_container.id+"_card_"+this.MIDCARD+"_link");

      window.location = url.href;
    }
  };

  //mouse
  this.start_mouse = function(e)
  {
    this.temp_x = e.clientX;
    this.temp_y = e.clientY;

    e.preventDefault();

    if(e.which === 1)
    {
      this.card_container.addEventListener("mousemove", this, false);
      document.onselectstart = function() {return false;};
      document.ondragstart = function(){return false;};
    }
  };

  this.end_mouse = function(e)
  {
    this.card_container.removeEventListener("mousemove", this, false);
    document.onselectstart = null;
    document.ondragstart = null;
  };

  //scroll
  this.scrollCards = function(e)
  {
    e.preventDefault();
    window.onmousewheel = document.onmousewheel = function() {return false;};
    this.scroll_with(e.detail ? e.detail/Math.abs(e.detail) : -e.wheelDelta/Math.abs(e.wheelDelta)); //= -1 or +1, depending on scroll direction
  };

  //event handler
  this.handleEvent = function(event)
  {
    switch(event.type)
    {
      case 'resize':
        this.create_boxes();
        break;
      case 'mousedown':
        this.start_mouse(event);
        break;
      case 'mouseup':
        this.end_mouse(event);
        break;
      case 'mousewheel':
      case 'DOMMouseScroll':
        this.scrollCards(event);
        break;
      case 'touchstart':
        this.start_touch(event);
        break;
      case 'touchend':
        this.end_touch(event);
        break;
      case 'mousemove':
      case 'touchmove':
        this.relocate(event);
        break;
      default:
        break;
    }
  };

  //and redo so if window changes size
  window.addEventListener("resize", this, false);

  //mouse
  this.card_container.addEventListener("mousedown", this, false);
  this.card_container.addEventListener("mouseup", this, false);

  //scroll
  this.card_container.onmouseout = function(){window.onmousewheel = document.onmousewheel = null;}; //sets scrollwheel to default
  this.card_container.addEventListener ("mousewheel", this, false);
  this.card_container.addEventListener ("DOMMouseScroll", this, false);

  //touch
  this.card_container.addEventListener("touchstart", this, false);
  this.card_container.addEventListener("touchend", this, false);
}
